﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Runtime.Serialization;

namespace QbservableCore.Serialization
{
    [DataContract]
    public class ListInitNode : ExpRepresentationBase
    {
        [DataMember]
        public NewInstanceNode NewExpression { get; set; }

        [DataMember]
        public ElementInitNode[] Initializers { get; set; }

        protected internal override Expression ToExpression(ExepressionBuilderCache exepressionBuilderCache)
        {
            ElementInit[] initializers = new ElementInit[Initializers.Length];
            for (int index = 0; index < initializers.Length; index++)
            {
                initializers[index] = Initializers[index].ToElementInit(exepressionBuilderCache);
            }
            NewExpression newExpression = (NewExpression)NewExpression.ToExpression(exepressionBuilderCache);
            return Expression.ListInit(newExpression, initializers);
        }

        protected override void TraverseChildren(Func<ExpRepresentationBase, ExpRepresentationBase> action)
        {
            NewExpression = (NewInstanceNode)NewExpression.Traverse(action);

            foreach (var initializer in Initializers)
            {
                initializer.TraverseChildren(action);
            }
        }

        public override string ToString()
        {
            string initializers = string.Join(", ", (object[])Initializers);
            return string.Format("{0} {{{1}}}", NewExpression, initializers);
        }
    }
}